//
//  HUDIndicatorView.swift
//  BWHUDKit
//
//  Created by zhuxuhong on 2022/3/16.
//

import BWUIKit


class HUDIndicatorRingLayer: CAShapeLayer {
    let thickness = CGFloat(3)
    
    override func draw(in ctx: CGContext) {
        backgroundColor = UIColor.clear.cgColor
        let rect = bounds.insetBy(dx: 10, dy: 10)
        let center = CGPoint(x: rect.midX, y: rect.midY)
        let radius = min(rect.width, rect.height)/2 - thickness/2
        
        let path = UIBezierPath(arcCenter: center, radius: radius, startAngle: 0, endAngle: (CGFloat.pi*2 - CGFloat.pi/6), clockwise: true)
        ctx.addPath(path.cgPath)
        ctx.setLineWidth(thickness)
        ctx.setLineCap(.round)
        ctx.setStrokeColor(HUD.shared.appearance.tintColor.cgColor)
        ctx.strokePath()
    }
}

public class HUDIndicatorView: View {
    var type: HUD.Square.LoadingType = .indicator {
        didSet{
            setupIndicator()
        }
    }
    
    lazy var activityView = UIActivityIndicatorView(style: .whiteLarge)
    lazy var imageView = UIImageView()
    lazy var ringLayer = HUDIndicatorRingLayer()
    
    private func commonInit(){
        activityView.hidesWhenStopped = true
        activityView.stopAnimating()
        backgroundColor = .clear
    }
    
    func setupIndicator() {
        switch type {
        case .indicator:
            activityView.transform = .init(scaleX: 1.25, y: 1.25)
            activityView.color = HUD.shared.appearance.tintColor
            addSubview(activityView)
            activityView.startAnimating()
            
        case .custom(let imgs):
            imageView.contentMode = .center
            addSubview(imageView)
            imageView.animationRepeatCount = .max
            imageView.animationDuration = CGFloat(imgs.count)/60
            imageView.animationImages = imgs
            imageView.startAnimating()
            
        case .ring:
            layer.addSublayer(ringLayer)
            ringLayer.setNeedsDisplay()
            CATransaction.disableActions()
            CATransaction.begin()
            let anim = CABasicAnimation()
            anim.fromValue = 0
            anim.toValue = CGFloat.pi*2
            anim.duration = 1
            anim.repeatCount = .infinity
            anim.isRemovedOnCompletion = false
            ringLayer.add(anim, forKey: "transform.rotation.z")
            CATransaction.commit()
        }
    }
    
    public override func didAwake() {
        commonInit()
    }
    public override func didInit() {
        commonInit()
    }
    
    public override func layoutSubviews() {
        super.layoutSubviews()
        
        ringLayer.frame = bounds
        activityView.frame = bounds
        imageView.frame = bounds
    }
}
